<template>
  <div class="user-management">
    <h2 class="title1" style="margin-bottom: 20px;">
      <el-icon :size="25">
        <Setting />
      </el-icon> 角色权限
    </h2>

    <!-- 查询区域 -->
    <el-card class="box-card query-card" shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div class="card-header">
          <span>操作项</span>
        </div>
      </template>
      <!-- 操作区域 -->
      <div class="action-bar">
        <span>角色ID：</span>
        <el-input v-model="filters.roleId" placeholder="请输入ID" style="width: 200px" />
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="success" plain @click="reset">重置</el-button>
        <div class="action-buttons">
          <el-button type="warning" plain @click="openAddDialog">新增</el-button>
          <el-button type="danger" plain @click="batchDelete">批量删除</el-button>
        </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="table-header">
          <div class="card-header">
            <span>数据列表</span>
          </div>
          <div class="action-buttons">
            <el-button type="success" plain>导入</el-button>
            <el-button type="primary" plain>导出</el-button>
          </div>
        </div>
      </template>

      <el-table :data="displayedRoles" border style="width: 100%; margin-top: 20px;"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="序号" align="center" width="100">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="角色ID" align="center" width="170"></el-table-column>
        <el-table-column prop="name" label="角色" align="center" width="220"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="350">
          <template #default="scope">
            <el-button type="primary" size="middle" @click="editRole(scope.row)">编辑</el-button>
            <el-button type="warning" size="middle" @click="rolePermission(scope.row)">权限绑定</el-button>
            <el-button type="danger" size="middle" @click="deleteRole(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background layout="total, sizes, prev, pager, next" :total="filteredRoles.length"
          :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增角色" width="500px" top="9vh">
      <div>
        <el-form :model="newRole" label-width="100px" align="left">
          <el-form-item label="角色KEY" label-for="id-input">
            <el-input id="id-input" v-model="newRole.key" placeholder="请输入KEY" />
          </el-form-item>
          <el-form-item label="角色名" label-for="name-input">
            <el-input id="name-input" v-model="newRole.name" placeholder="请输入角色名" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="newRole.remark" placeholder="请输入" maxlength="100" show-word-limit />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddRole">确定</el-button>
      </template>
    </el-dialog>

    <!--权限弹窗-->
    <el-dialog v-model="rolePermissionDialogVisible" :title="`${activeRoleName}-权限绑定`" width="50%" top="9vh">
      <el-tree ref="permTreeRef" :data="permTreeData" show-checkbox node-key="id" :default-checked-keys="checkedPermIds"
        :props="permTreeProps" highlight-current style="max-height: 600px; overflow-y: auto; margin-top: 10px;">
        <template #default="{ node, data }">
          <span>{{ data.label }}</span>
          <span v-if="data.remark" style="color:#999;font-size:12px;margin-left:8px;">{{ data.remark }}</span>
        </template>
      </el-tree>
      <template #footer>
        <el-button @click="rolePermissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRolePermissionTree">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'

// 权限弹窗控制
const rolePermissionDialogVisible = ref(false)
// 当前激活的角色
const activeRole = ref();
const activeRoleName = ref('');
const addDialogVisible = ref(false);

// 数据
const roles = ref([]) // 动态获取的角色列表
const permissions = ref([]) // 动态获取的权限列表
const originalPermIds = ref([])

const permTreeData = ref([])
const checkedPermIds = ref([])
const permTreeRef = ref(null)
const permTreeProps = {
  children: 'children',
  label: 'label'
}

// 权限树构建函数
function buildPermTree(permList) {
  const root = {}
  for (const perm of permList) {
    const keys = perm.key.split(':')
    let node = root
    keys.forEach((k, idx) => {
      node.children = node.children || []
      let child = node.children.find(c => c.label === k)
      if (!child) {
        child = {
          label: k,
          id: idx === keys.length - 1 ? perm.id : `${keys.slice(0, idx + 1).join(':')}`,
          remark: idx === keys.length - 1 ? perm.remark : '',
          children: []
        }
        node.children.push(child)
      }
      node = child
    })
  }
  // 只返回第一层children
  return root.children || []
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await axios.get('http://localhost:8181/role/list', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      roles.value = response.data.data.map(role => ({
        id: role.roleId,
        name: role.roleName,
        remark: role.remark
      }))
      ElMessage.success('获取角色列表成功')
    } else {
      ElMessage.error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    const response = await axios.get('http://localhost:8181/perm/list', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      permissions.value = response.data.data.map(perm => ({
        id: perm.permId,
        key: perm.permKey,
        remark: perm.remark
      }))
      ElMessage.success('获取权限列表成功')
    } else {
      ElMessage.error(response.data.message || '获取权限列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 页面加载时获取角色和权限
onMounted(() => {
  fetchRoles()
  fetchPermissions()
})

// 筛选条件
const filters = reactive({
  roleId: '', // 编号过滤条件
});

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤后的数据
const filteredRoles = computed(() => {
  return roles.value.filter((role) =>
    filters.roleId ? role.id.includes(filters.roleId) : true
  );
});

// 当前页显示的数据
const displayedRoles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredRoles.value.slice(start, end);
});


// 查询功能
const search = () => {
  currentPage.value = 1; // 重置到第一页
};

// 重置功能
const reset = () => {
  filters.roleId = ''; // 清空编号过滤条件
  currentPage.value = 1; // 重置到第一页
};


const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

// 批量删除
const selectedRoles = ref([])
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}
const batchDelete = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要删除的角色')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的角色吗？', '提示', {
      type: 'warning'
    })
    // 依次调用已有的删除方法
    for (const role of selectedRoles.value) {
      await deleteRole(role)
    }
    ElMessage.success('批量删除成功')
    // 清空选择
    selectedRoles.value = []
    fetchRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message))
    }
  }
}
const newRole = reactive({
  key: '',
  name: '',
  remark: '',
});
// 新增
const openAddDialog = () => {
  addDialogVisible.value = true;
  // 重置表单数据
  newRole.key = '';
  newRole.name = '';
  newRole.remark = '';
};
const confirmAddRole = async () => {
  if (!newRole.key || !newRole.name || !newRole.remark) {
    ElMessage.warning('请填写完整信息');
    return;
  }
  const response = await axios.post('http://localhost:8181/role/add', {
    roleKey: newRole.key,
    roleName: newRole.name,
    remark: newRole.remark
  }, {
    headers: {
      [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
    }
  })
  if (response.data.code !== 200) {
    ElMessage.error('新增角色失败');
    return;
  }
  ElMessage.success('新增角色成功');
  addDialogVisible.value = false; // 关闭弹窗
  fetchRoles(); // 重新获取角色列表
};

// 编辑
const editRole = (role) => {
  ElMessage.info(`编辑角色：${role.name}`)
}

// 权限绑定
const rolePermission = async (role) => {
  activeRole.value = role.id
  activeRoleName.value = role.name
  rolePermissionDialogVisible.value = true
  try {
    // 获取所有权限
    const permRes = await axios.get('http://localhost:8181/perm/list', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (permRes.data.code === 200) {
      const permList = permRes.data.data.map(perm => ({
        id: perm.permId,
        key: perm.permKey,
        remark: perm.remark
      }))
      permTreeData.value = buildPermTree(permList)
    } else {
      ElMessage.error('获取权限列表失败')
      return
    }
    // 获取当前角色已绑定权限
    const bindRes = await axios.get(`http://localhost:8181/role/${activeRole.value}`, {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (bindRes.data.code === 200) {
      checkedPermIds.value = bindRes.data.data.map(perm => perm.permId)
    } else {
      checkedPermIds.value = []
    }
    await nextTick()
    // 设置选中
    permTreeRef.value && permTreeRef.value.setCheckedKeys(checkedPermIds.value)
    // 自动展开所有节点
    permTreeRef.value && permTreeRef.value.expandAll && permTreeRef.value.expandAll()
    // 若没有expandAll方法则递归展开
    if (permTreeRef.value && permTreeRef.value.store) {
      permTreeRef.value.store.nodesMap &&
        Object.values(permTreeRef.value.store.nodesMap).forEach(node => node.expanded = true)
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 确认权限绑定
const confirmRolePermissionTree = async () => {
  const checkedKeys = permTreeRef.value.getCheckedKeys(true)
  // 之前已绑定的权限
  const oldIds = checkedPermIds.value || []
  // 新增的权限
  const addIds = checkedKeys.filter(id => !oldIds.includes(id))
  // 需要解绑的权限
  const removeIds = oldIds.filter(id => !checkedKeys.includes(id))

  try {
    // 先绑定新增
    if (addIds.length > 0) {
      for (const id of addIds) {
        const response = await axios.post(
          `http://localhost:8181/perm/bind?roleId=${activeRole.value}&permId=${id}`,
          null,
          {
            headers: {
              [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
            }
          }
        )
        if (response.data.code !== 200) {
          ElMessage.error(`绑定权限 ${id} 失败`)
          return
        }
      }
      ElMessage.success('权限绑定成功')
    }
    // 再解绑减少
    if (removeIds.length > 0) {
      for (const id of removeIds) {
        const response = await axios.delete(
          `http://localhost:8181/perm/unbind?roleId=${activeRole.value}&permId=${id}`,
          {
            headers: {
              [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
            }
          }
        )
        if (response.data.code !== 200) {
          ElMessage.error(`解绑权限 ${id} 失败`)
          return
        }
      }
      ElMessage.success('权限解绑成功')
    }
    ElMessage.success(`${activeRoleName.value}权限修改成功`)
    // 更新原始权限id
    checkedPermIds.value = [...checkedKeys]
    originalPermIds.value = [...checkedKeys]
    rolePermissionDialogVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('权限绑定失败')
  }
}
// 删除
const deleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 ${role.name} 吗？`, '提示', {
      type: 'warning'
    })
    const response = await axios.delete(`http://localhost:8181/role/delete/${role.id}`, {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code !== 200) {
      ElMessage.error('删除角色失败')
      return
    }
    ElMessage.success('删除成功')
    fetchRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

</script>

<style scoped>
.user-management {
  min-height: 100vh;
}

.box-card {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.query-card {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}


.action-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  /* 如果屏幕宽度不足，自动换行 */
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title1 {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.action-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

/* 新增滚动容器样式 */
.perm-table-scroll {
  max-height: 600px;
  /* 限制最大高度 */
  overflow-y: auto;
  /* 超出部分滚动 */
  margin-top: 10px;
}
</style>